import { Request, Response } from 'express'
import classesService from '../../service/classesService'
import majorService from '../../service/majorService'
import { validate } from './validate'
import studentService from '../../service/studentService'

class ClassesController {
  // 创建
  async createClasses(req: Request, res: Response) {
    const form = req.body
    const validateRes = validate(form)
    if (validateRes) return res.gem(validateRes)

    const classes = await classesService.findByClassesName(form.class_name)
    if (classes) return res.gem('该班级名称已存在！')
    // 根据专业名称查询，获取到对应专业的id
    const major = await majorService.findByMajorName(form.major_name)
    if (!major) return res.gem('该专业不存在!')
    form.mid = String(major.id)
    const saveRes = await classesService.saveClasses(form)
    if (saveRes) {
      res.gsm('创建成功！')
    } else {
      res.gem('创建失败！')
    }
  }

  // 修改
  async updateClasses(req: Request, res: Response) {
    const form = req.body
    const cid = form.id
    delete form.id
    // 如果改变了专业，其专业id也要改变
    const major = await majorService.findByMajorName(form.major_name)
    form.mid = major.id.toString()
    const result = await classesService.updateClasses(cid, form)
    if (result.affected < 0) return res.gem('修改信息失败！')
    const c = await classesService.findById(cid)
    res.gsmd(c, '信息修改成功！')
  }

  // 根据班级名称模糊查询
  async findByClassNameKey(req: Request, res: Response) {
    let label = ''
    let value = ''
    Object.keys(req.body).forEach(item => {
      if (item.includes('name')) {
        label = item
        value = req.body[item]
      }
    })

    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size

    const count = await classesService.findByClassNameKeyCount(label, value)
    const classes = await classesService.findByClassNameKey(label, value, skip, page_size)
    if (!classes) res.gem('查无数据！')
    res.gsmdl(count, classes)
  }

  // 查找全部
  async findAll(req: Request, res: Response) {
    const classes = await classesService.findAll()
    res.gsmd(classes)
  }

  // 删除班级
  async deleteClassesById(req: Request, res: Response) {
    const { id } = req.params
    const classes = await classesService.findById(id)
    const stu = await studentService.findStuByClass(classes.class_name)
    if (stu) return res.gem('该班级下还有学生，不可删除！')
    const result = await classesService.deleteClassesById(id)
    if (result.affected > 0) {
      res.gsm('删除成功！')
    }
  }

}

export default new ClassesController()